import 'dart:async';
import 'dart:collection';
import 'dart:isolate';

import '../service/log_utils.dart';

class ReadWriteLock {
  ReadWriteLock();

  int _readers = 0;
  bool _isWriting = false;
  final Queue<Completer<void>> _readQueue = Queue<Completer<void>>();
  final Queue<Completer<void>> _writeQueue = Queue<Completer<void>>();

  /// 请求读锁
  ///
  /// 当有写操作在进行或等待时，读操作将被加入等待队列
  Future<void> acquireRead() async {
    if (_isWriting || _writeQueue.isNotEmpty) {
      final completer = Completer<void>();
      _readQueue.add(completer);
      await completer.future;
    }
    _readers++;
  }

  /// 释放读锁
  ///
  /// 释放后会触发队列处理，检查是否有等待的写操作
  void releaseRead() {
    _readers--;
    _processQueues();
  }

  /// 请求写锁
  ///
  /// 当有读操作或其他写操作在进行时，写操作将被加入等待队列
  Future<void> acquireWrite() async {
    if (_readers > 0 || _isWriting) {
      final completer = Completer<void>();
      _writeQueue.add(completer);
      await completer.future;
    }
    _isWriting = true;
  }

  /// 释放写锁
  ///
  /// 释放后会触发队列处理，优先处理等待的写操作
  void releaseWrite() {
    _isWriting = false;
    _processQueues();
  }

  /// 释放所有资源
  void clear() {
    try {
      releaseWrite();
      releaseRead();
      _readQueue.clear();
      _writeQueue.clear();
    } catch (e) {
      LogUtils.d('读写锁 释放资源失败: $e');
    }
  }

  /// 处理等待队列
  ///
  /// 优先处理写操作，如果没有写操作则处理所有等待的读操作
  void _processQueues() {
    if (_isWriting || _readers > 0) {
      return;
    }

    if (_writeQueue.isNotEmpty) {
      _isWriting = true;
      _writeQueue.removeFirst().complete();
    } else {
      while (_readQueue.isNotEmpty) {
        _readers++;
        _readQueue.removeFirst().complete();
      }
    }
  }

  /// 使用读锁执行操作
  ///
  /// [action] 要执行的读操作
  /// 返回读操作的结果
  Future<T> read<T>(Future<T> Function() action) async {
    await acquireRead();
    try {
      return await action();
    } finally {
      releaseRead();
    }
  }

  /// 使用写锁执行操作
  ///
  /// [action] 要执行的写操作
  /// 返回写操作的结果
  Future<T> write<T>(Future<T> Function() action) async {
    await acquireWrite();
    try {
      return await action();
    } finally {
      releaseWrite();
    }
  }

  /// 在 Isolate 中执行读操作
  ///
  /// [action] 要在 Isolate 中执行的读操作
  /// 返回读操作的结果
  Future<T> readIsolate<T>(Future<T> Function() action) async {
    return await Isolate.run(() async {
      await acquireRead();
      try {
        return await action();
      } finally {
        releaseRead();
      }
    });
  }

  /// 在 Isolate 中执行写操作
  ///
  /// [action] 要在 Isolate 中执行的写操作
  /// 返回写操作的结果
  Future<T> writeIsolate<T>(Future<T> Function() action) async {
    return await Isolate.run(() async {
      await acquireWrite();
      try {
        return await action();
      } finally {
        releaseWrite();
      }
    });
  }
}
